from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from django.db.models import Q
import csv
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
from openpyxl.utils import get_column_letter
from .models import Bicycle, ViolationRecord, CollegeUser


@login_required
def export_bikes_excel(request):
    """导出自行车数据为Excel"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    # 获取查询参数
    search = request.GET.get('search', '')
    category = request.GET.get('category', '')
    college_filter = request.GET.get('college', '')
    
    # 构建查询
    if college_user.is_super_admin:
        bikes = Bicycle.objects.all()
        if college_filter:
            bikes = bikes.filter(college=college_filter)
    else:
        bikes = Bicycle.objects.filter(college=college_user.college)
    
    if search:
        bikes = bikes.filter(
            Q(bike_number__icontains=search) |
            Q(owner_name__icontains=search) |
            Q(owner_student_id__icontains=search) |
            Q(model__icontains=search)
        )
    
    if category:
        bikes = bikes.filter(category=category)
    
    # 创建Excel工作簿
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "自行车数据"
    
    # 设置标题行
    headers = [
        '编号', '型号', '所有人', '学号', '类别', '学院', '班级', 
        '联系电话', '购买日期', '颜色', '备注'
    ]
    
    # 设置标题样式
    header_font = Font(bold=True, color="FFFFFF")
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_alignment = Alignment(horizontal="center", vertical="center")
    
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = header_alignment
    
    # 添加数据行
    for row, bike in enumerate(bikes, 2):
        ws.cell(row=row, column=1, value=bike.bike_number)
        ws.cell(row=row, column=2, value=bike.model)
        ws.cell(row=row, column=3, value=bike.owner_name)
        ws.cell(row=row, column=4, value=bike.owner_student_id)
        ws.cell(row=row, column=5, value=bike.get_category_display())
        ws.cell(row=row, column=6, value=bike.get_college_display())
        ws.cell(row=row, column=7, value=bike.class_name)
        ws.cell(row=row, column=8, value=bike.phone_number)
        ws.cell(row=row, column=9, value=bike.purchase_date.strftime('%Y-%m-%d') if bike.purchase_date else '')
        ws.cell(row=row, column=10, value=bike.color)
        ws.cell(row=row, column=11, value=bike.notes)
    
    # 自动调整列宽
    for column in ws.columns:
        max_length = 0
        column_letter = get_column_letter(column[0].column)
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = min(max_length + 2, 50)
        ws.column_dimensions[column_letter].width = adjusted_width
    
    # 创建响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename="bikes_export.xlsx"'
    
    wb.save(response)
    return response


@login_required
def export_bikes_csv(request):
    """导出自行车数据为CSV"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    # 获取查询参数
    search = request.GET.get('search', '')
    category = request.GET.get('category', '')
    college_filter = request.GET.get('college', '')
    
    # 构建查询
    if college_user.is_super_admin:
        bikes = Bicycle.objects.all()
        if college_filter:
            bikes = bikes.filter(college=college_filter)
    else:
        bikes = Bicycle.objects.filter(college=college_user.college)
    
    if search:
        bikes = bikes.filter(
            Q(bike_number__icontains=search) |
            Q(owner_name__icontains=search) |
            Q(owner_student_id__icontains=search) |
            Q(model__icontains=search)
        )
    
    if category:
        bikes = bikes.filter(category=category)
    
    # 创建CSV响应
    response = HttpResponse(content_type='text/csv; charset=utf-8-sig')
    response['Content-Disposition'] = 'attachment; filename="bikes_export.csv"'
    
    # 写入BOM以支持中文
    response.write('\ufeff')
    
    writer = csv.writer(response)
    
    # 写入标题行
    writer.writerow([
        '编号', '型号', '所有人', '学号', '类别', '学院', '班级', 
        '联系电话', '购买日期', '颜色', '备注'
    ])
    
    # 写入数据行
    for bike in bikes:
        writer.writerow([
            bike.bike_number,
            bike.model,
            bike.owner_name,
            bike.owner_student_id,
            bike.get_category_display(),
            bike.get_college_display(),
            bike.class_name,
            bike.phone_number,
            bike.purchase_date.strftime('%Y-%m-%d') if bike.purchase_date else '',
            bike.color,
            bike.notes
        ])
    
    return response


@login_required
def export_users_excel(request):
    """导出用户数据为Excel（仅超级管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        if not college_user.is_super_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:admin_dashboard')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    # 获取所有用户
    users = CollegeUser.objects.all().order_by('-created_at')
    
    # 创建Excel工作簿
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "用户数据"
    
    # 设置标题行
    headers = ['用户名', '学院', '是否管理员', '是否超级管理员', '创建时间']
    
    # 设置标题样式
    header_font = Font(bold=True, color="FFFFFF")
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_alignment = Alignment(horizontal="center", vertical="center")
    
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = header_alignment
    
    # 添加数据行
    for row, user in enumerate(users, 2):
        ws.cell(row=row, column=1, value=user.user.username)
        ws.cell(row=row, column=2, value=user.get_college_display())
        ws.cell(row=row, column=3, value='是' if user.is_admin else '否')
        ws.cell(row=row, column=4, value='是' if user.is_super_admin else '否')
        ws.cell(row=row, column=5, value=user.created_at.strftime('%Y-%m-%d %H:%M:%S'))
    
    # 自动调整列宽
    for column in ws.columns:
        max_length = 0
        column_letter = get_column_letter(column[0].column)
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = min(max_length + 2, 50)
        ws.column_dimensions[column_letter].width = adjusted_width
    
    # 创建响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename="users_export.xlsx"'
    
    wb.save(response)
    return response


@login_required
def export_violations_excel(request):
    """导出违章记录数据为Excel"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    # 获取违章记录
    if college_user.is_super_admin:
        violations = ViolationRecord.objects.all().order_by('-created_at')
    else:
        violations = ViolationRecord.objects.filter(
            bicycle__college=college_user.college
        ).order_by('-created_at')
    
    # 创建Excel工作簿
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "违章记录"
    
    # 设置标题行
    headers = [
        '自行车编号', '违章类型', '描述', '检查人', '状态', '创建时间', '更新时间'
    ]
    
    # 设置标题样式
    header_font = Font(bold=True, color="FFFFFF")
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_alignment = Alignment(horizontal="center", vertical="center")
    
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = header_alignment
    
    # 添加数据行
    for row, violation in enumerate(violations, 2):
        ws.cell(row=row, column=1, value=violation.bicycle.bike_number)
        ws.cell(row=row, column=2, value=violation.get_violation_type_display())
        ws.cell(row=row, column=3, value=violation.description)
        ws.cell(row=row, column=4, value=violation.inspector_name)
        ws.cell(row=row, column=5, value=violation.get_status_display())
        ws.cell(row=row, column=6, value=violation.created_at.strftime('%Y-%m-%d %H:%M:%S'))
        ws.cell(row=row, column=7, value=violation.updated_at.strftime('%Y-%m-%d %H:%M:%S'))
    
    # 自动调整列宽
    for column in ws.columns:
        max_length = 0
        column_letter = get_column_letter(column[0].column)
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = min(max_length + 2, 50)
        ws.column_dimensions[column_letter].width = adjusted_width
    
    # 创建响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename="violations_export.xlsx"'
    
    wb.save(response)
    return response
